<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from "vue";
const {proxy} = getCurrentInstance();
import {
  createLogin,
  selectLoginById,
  allowUseLoginName,
  updateLoginById,
  searchFields,
  updateSubLoginPassword
} from "@/api/basal.js";
import {ResultEnums} from "@/enums/ResultStatusEnums.js";
import {useRouter} from "vue-router";
import ExpandFields from "@/components/debris/ExpandFields.vue";
import Alert from "@/components/debris/Alert.vue"
const router = useRouter();
const formRef = ref(null)
const errorMessageInfo = reactive({alert:false,level:2,title:'',content:''})
const loginNamePass = ref(true)
const loginPasswordPass = ref(true)
const lastPasswordPass = ref(null)
const currentSystemCode = ref(import.meta.env.VITE_SYSTEM_CODE)
const form = reactive({isEnable:true, id:proxy.$route.query.id,sort:0, loginName:'',logoffTime:'',reAuthTime:'',
        isLock:false,loginPassword:'',moduleName:'user',expands:{}});
const fields = ref([])

onMounted(() => {
  onLoad(proxy.$route.query.id).then(data=>{
    Object.keys(data).forEach(key => {
      form[key] = data[key]
    })
    loadFields(currentSystemCode.value,form.moduleName,form.id||'').then(result => {
      fields.value = result
    })
  })
})

async function onLoad(id){
  let data
  if(id){
    let result = await selectLoginById(id,form.moduleName);
    data = result.code === ResultEnums.SUCCESS?result.data:{}
  }else {
    data = {}
  }
  return data
}

async function loadFields(systemCode,moduleName,loginId){
  const result = await searchFields(systemCode,moduleName,{isEnable:true,loginId:loginId})
  return result.code === ResultEnums.SUCCESS? result.data : []
}

async function confirm(e){
  e.preventDefault();
  if (formRef.value.checkValidity() && loginNamePass.value && loginPasswordPass.value) {
    if(form.id){
      const result = await updateLoginById(form.id,form)
      if(result.code === ResultEnums.SUCCESS ){
        router.go(-1);
      }else {
        errorMessageInfo.alert = true;
        errorMessageInfo.title = '修改操作失败提示'
        errorMessageInfo.level = 1
        errorMessageInfo.content = result.message
      }
    } else {
      const result = await createLogin(form)
      if(result.code === ResultEnums.SUCCESS ){
        router.go(-1);
      }else {
        errorMessageInfo.alert = true;
        errorMessageInfo.title = '创建操作失败提示'
        errorMessageInfo.level = 1
        errorMessageInfo.content = result.message
      }
    }
  } else {
    formRef.value.reportValidity();
  }
}

async function validationLoginName(loginName,id){
  const result = await allowUseLoginName(loginName,id)
  if(result.code === ResultEnums.SUCCESS){
    loginNamePass.value = result.data
  }else {
    loginNamePass.value = true
  }
}

async function validationPassword(password,lastPassword){
  if(password && lastPassword){
    loginPasswordPass.value = (password === lastPassword)
  }else {
    loginPasswordPass.value = true
  }
}

const password = reactive({newPassword: "",affirmPassword: ""});
const errors = reactive({})
const alertInfo = reactive({alert:false,level:2,title:'',content:''})
async function confirmUpdatePassword(e,loginId){
  e.preventDefault();
  await resetErrors()
  const newPassword = password.newPassword;
  if(!newPassword) {
    errors['newPassword'] = '请输入新密码';
    return;
  }
  const affirmPassword = password.affirmPassword;
  if(!affirmPassword) {
    errors['affirmPassword'] = '请再次输入新密码';
    return;
  }

  if(newPassword !== affirmPassword) {
    errors['newPassword'] = '与再次输入密码不一致,请修改';
    errors['affirmPassword'] = '与新输入密码不一致,请修改';
    return;
  }
  const result = await updateSubLoginPassword(loginId, newPassword);
  if(result.code === ResultEnums.SUCCESS ){
    const flag = result.data;
    if(flag){
      await resetPasswordParam()
      alertInfo.alert = true;
      alertInfo.title = '修改密码成功提示'
      alertInfo.level = 2
      alertInfo.content = '修改密码成功,作用重新登录'
    }else{
      alertInfo.alert = true;
      alertInfo.title = '修改密码失败提示'
      alertInfo.level = 1
      alertInfo.content = '修改密码失败,请稍后重试'
    }
  }else {
    alertInfo.alert = true;
    alertInfo.title = '修改密码失败提示'
    alertInfo.level = 1
    alertInfo.content = result.message
  }
}
async function resetErrors(){
  Object.keys(errors).forEach(key => {
     delete errors[key]
  })
}
async function resetPasswordParam(){
  Object.keys(password).forEach(key => {
    password[key] = ''
  })
}
</script>

<template>
  <h1 class="app-page-title" v-if="proxy.$route.meta">
    <a href="#" @click="(e)=>{e.preventDefault();router.go(-1);}"> <i class="bi bi-reply-all"></i></a> {{ proxy.$route.meta.theme }}
  </h1>
  <hr class="mb-4">
  <div class="row g-4 settings-section">
    <div class="col-12 col-md-8">
      <div class="app-card app-card-settings shadow-sm p-4">
        <div class="app-card-body">
          <form class="settings-form" ref="formRef">
            <div class="mb-3">
              <label for="setting-input-1" class="form-label">账号名称</label>
              <input type="text" aria-describedby="validationLoginName" class="form-control"
                     :class="loginNamePass||' is-invalid '"  @blur="validationLoginName(form.loginName,form.id)" v-model="form.loginName" required>
              <div id="validationLoginName" class="invalid-feedback" v-if="!loginNamePass">
                账号名称已存在,请修改后重试
              </div>
            </div>
            <template v-if="!form.id">
              <div class="mb-3">
                <label for="setting-input-2" class="form-label">账号密码</label>
                <input type="password" class="form-control" id="setting-input-2" @blur="validationPassword(form.loginPassword,lastPasswordPass)"
                       v-model="form.loginPassword" required>
              </div>
              <div class="mb-3">
                <label for="setting-input-3" class="form-label">再次输入密码</label>
                <input type="password" :class="loginPasswordPass||' is-invalid '" class="form-control"  @blur="validationPassword(form.loginPassword,lastPasswordPass)"
                       id="setting-input-3" v-model="lastPasswordPass" required>
                <div id="validationLoginPassword" class="invalid-feedback" v-if="!loginPasswordPass">
                  两次输入的密码不一致,请修改后重试
                </div>
              </div>
            </template>
            <ExpandFields v-if="fields" :fieldItems="fields" v-model="form.expands"/>
            <div class="mb-3">
              <label for="setting-input-4" class="form-label">过期时间</label>
              <el-date-picker id="setting-input-4" class="form-control"  v-model="form.logoffTime" type="date" value-format="YYYY-MM-DD HH:mm:ss"/>
            </div>
            <div class="mb-3">
              <label for="setting-input-5" class="form-label">重新认证时间</label>
              <el-date-picker id="setting-input-5" class="form-control"  v-model="form.reAuthTime" type="date" value-format="YYYY-MM-DD HH:mm:ss"/>
            </div>
            <div class="mb-3">
              <label for="setting-input-6" class="form-label">账号排序</label>
              <input type="number" class="form-control" id="setting-input-6" v-model="form.sort" required>
            </div>
            <div class="form-check form-switch mb-3">
              <input class="form-check-input" type="checkbox" id="settings-switch-7" v-model="form.isLock">
              <label class="form-check-label" for="settings-switch-7">锁定</label>
            </div>
            <div class="form-check form-switch mb-3">
              <input class="form-check-input" type="checkbox" id="settings-switch-8" v-model="form.isEnable">
              <label class="form-check-label" for="settings-switch-8">启用</label>
            </div>
            <Alert :level="errorMessageInfo.level" :title="errorMessageInfo.title" :content="errorMessageInfo.content"
                   v-model="errorMessageInfo.alert"></Alert>
            <button type="submit" class="btn app-btn-primary" @click="confirm">确认</button>
          </form>
        </div><!--//app-card-body-->

      </div><!--//app-card-->
    </div>
    <div class="col-12 col-md-4">
      <div class="app-card shadow-sm  flex-column align-items-start" v-if="form.id">
        <div class="app-card-header p-3 border-bottom-0">
          <div class="row align-items-center gx-3">
            <div class="col-auto">
              <div class="app-icon-holder">
                <i class="bi bi-shield-check"></i>
              </div><!--//icon-holder-->
            </div><!--//col-->
            <div class="col-auto">
              <h4 class="app-card-title">密码重置</h4>
            </div><!--//col-->
          </div><!--//row-->
        </div><!--//app-card-header-->
        <div class="app-card-body px-4 w-100">
          <div class="item border-bottom py-3">
            <div class="row justify-content-between align-items-center">
              <div class="col-auto">
                <div class="item-label"><strong>新密码</strong></div>
                <div class="item-data">
                  <input id="signin-password" type="password" class="form-control border-0" v-model="password.newPassword"
                         :class="(errors.hasOwnProperty('newPassword')) && 'is-invalid'"   aria-describedby="newPassword" required="required">
                  <div id="newPassword" class="invalid-feedback" v-if="(errors.hasOwnProperty('newPassword'))">{{errors['newPassword']}}</div>
                </div>
              </div><!--//col-->
            </div><!--//row-->
          </div><!--//item-->
          <div class="item border-bottom py-3">
            <div class="row justify-content-between align-items-center">
              <div class="col-auto">
                <div class="item-label"><strong>再次确认密码</strong></div>
                <div class="item-data">
                  <input id="signin-password" type="password" class="form-control border-0" v-model="password.affirmPassword"
                         :class="(errors.hasOwnProperty('affirmPassword')) && 'is-invalid'"   aria-describedby="affirmPassword" required="required">
                  <div id="affirmPassword" class="invalid-feedback" v-if="(errors.hasOwnProperty('affirmPassword'))">{{errors['affirmPassword']}}</div>
                </div>
              </div><!--//col-->
            </div><!--//row-->
          </div><!--//item-->
          <div class="item py-3" v-if="alertInfo.alert">
            <Alert :level="alertInfo.level" :title="alertInfo.title" :content="alertInfo.content" v-model="alertInfo.alert"></Alert>
          </div>
        </div><!--//app-card-body-->
        <div class="app-card-footer p-4 mt-auto">
          <a class="btn app-btn-secondary" href="#" @click="confirmUpdatePassword($event,form.id)">确认提交</a>
        </div><!--//app-card-footer-->

      </div><!--//app-card-->
    </div>
  </div><!--//row-->
</template>

<style scoped>
:deep(.el-date-editor) {
  height: 2.5rem;
  width: 100%;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 0 var(--el-input-border-color,var(--el-border-color)) inset;
}
</style>